package fon.rm2.server.rs232;

import java.io.*;

import javax.comm.*;

//import com.sun.org.apache.bcel.internal.generic.ALOAD;

import java.sql.SQLException;
//import java.util.*;

public class CommunicationClass implements SerialPortEventListener {
	
	 //static Enumeration ports;
	 static CommPortIdentifier pID;
	 InputStream inStream;
	 static OutputStream outStream;
	 SerialPort serPort;

     byte[] cardIDBytes = null;

	 
	 
	 
  public CommunicationClass() throws Exception{
/*
	    ports = CommPortIdentifier.getPortIdentifiers();

	    while (ports.hasMoreElements()) {
	      pID = (CommPortIdentifier) ports.nextElement();
	      if (pID.getPortType() == CommPortIdentifier.PORT_SERIAL) {
	        if (pID.getName().equals("COM50")) {
	        	System.out.println("COM50 found");
	        	init();
	        	break;
	        }
	      }
	    }
	*/  
	    pID = CommPortIdentifier.getPortIdentifier("COM50");
	    System.out.println("com50 found");
	    init();
  }
  
  public void init() throws Exception{
	    
	  	serPort = (SerialPort) pID.open("COM50",2000);
	    inStream = serPort.getInputStream();
	    outStream = serPort.getOutputStream();
	    serPort.addEventListener(this);
	    serPort.notifyOnDataAvailable(true);
	    serPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
	        SerialPort.PARITY_NONE);
  }

	public void serialEvent(SerialPortEvent event) {
		if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
			String recieved = "";
			byte ch = 0;
			try {
				while ((ch = (byte) inStream.read()) != -1) {
					if (ch == 64) {
						serialportWrite(true);
					}else
					recieved += (Character.toString((char) ch));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("recieved " + recieved);

			DatabaseConnectionClass dbc = new DatabaseConnectionClass();
			boolean allowed = false;
			try {

				allowed = dbc.checkUser(recieved);
				dbc.writeHistory(recieved, allowed);
				serialportWrite(allowed);
				System.out.println("allowed: " +allowed);
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
  }

	private void serialportWrite(boolean allowed) throws IOException {
		if (allowed){
			 outStream.write("Y".getBytes());
		}else{
			outStream.write("N".getBytes());
		}

	}

}
